// Enhanced front-end interaction for the guessing game
document.addEventListener("DOMContentLoaded", () => {
  const input = document.querySelector(".guess-input");
  if (input) {
    input.focus();
  }

  // Load history on page load
  loadHistory();
});

// Show game history modal
function showHistory() {
  const modal = document.getElementById("history-modal");
  if (modal) {
    modal.style.display = "block";
    loadHistory();
  }
}

// Close history modal
function closeHistory() {
  const modal = document.getElementById("history-modal");
  if (modal) {
    modal.style.display = "none";
  }
}

// Load history from server
async function loadHistory() {
  try {
    const response = await fetch("/history");
    const history = await response.json();
    displayHistory(history);
  } catch (error) {
    console.error("Error loading history:", error);
  }
}

// Display history in the modal
function displayHistory(history) {
  const historyList = document.getElementById("history-list");
  if (!historyList) return;

  if (history.length === 0) {
    historyList.innerHTML = '<p class="message-muted">暂无游戏记录，开始你的第一局游戏吧！</p>';
    return;
  }

  const historyHTML = history
    .slice()
    .reverse()
    .map((game, index) => {
      const date = new Date(game.timestamp);
      const dateStr = date.toLocaleString("zh-CN", {
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });

      const difficultyLabels = {
        easy: "简单",
        medium: "中等",
        hard: "困难",
        expert: "专家",
        custom: "自定义",
      };

      return `
        <div class="history-item">
          <div class="history-header">
            <span class="history-difficulty">${
              difficultyLabels[game.difficulty] || game.difficulty
            }</span>
            <span class="history-attempts">${game.attempts} 次</span>
          </div>
          <div class="history-details">
            目标数字: <strong>${game.target}</strong> | ${dateStr}
          </div>
        </div>
      `;
    })
    .join("");

  historyList.innerHTML = historyHTML;
}

// Close modal when clicking outside
window.onclick = function (event) {
  const modal = document.getElementById("history-modal");
  if (event.target === modal) {
    modal.style.display = "none";
  }
};
  
  